import neon.sync
import neon.atom as atom
import neon.version as version
import neon.db_backend

class DummyC: 
    def __init__(self):
	self.id_ = 'test'
	self.init_db_ = True

class DummyS: pass

class DummyT:
    def __init__(self):
	self.a = []

    def connect(self):
	self.a.append('connect')

    def update_iterators(self, v):
	self.a.append('update_iterators %s,%s' % v)

    def check_pending_iterators(self):
	self.a.append('check_pending_iterators')
	
sqlite = neon.db_backend.Sqlite(':memory:', True)
dummy_s = DummyS()
dummy_s.db_ = sqlite
dummy_t = DummyT()

atom_st = neon.atom.AtomStore(dummy_s, True, None)

sync = neon.sync.Sync(config_inst = DummyC(),
	              db = sqlite, 
	              atom_store = atom_st, 
	              transport = dummy_t)
atom_st.sync_ = sync
atom_st.db_ = sqlite

# register some types

sqlite.execute('CREATE TABLE tab1 (guid, id)')
t1 = atom.AtomType('testatom')
t1.add_table('tab1', ('SELECT guid FROM tab1 WHERE id = ?', ['id']))
atom_st.reg_type(t1)

# now put some fake entries into the database
def add_atom(id):
    g = atom_st.get_new_guid()
    v = version.Vector([g.as_tuple()])
    type = 'testatom'
    deleted = False
    local = True
    sqlite.execute('INSERT INTO neon_atom_meta VALUES (?,?,?,?,?)',
	           (g.to_raw(), v.to_raw(), type, deleted, local))
    sqlite.execute('INSERT INTO tab1 VALUES (?, ?)', (g.to_raw(), id))

class Inc:
    c = 0

    def __init__(self):
	self.c = Inc.c
	Inc.c = Inc.c + 1

    def __call__(self):
	return 'atom-%d' % self.c

i = Inc()

add_atom(i())
add_atom(i())
add_atom(i())

sync.scan_local()

add_atom(i())
add_atom(i())

sync.scan_local()

add_atom(i())
add_atom(i())

sync.scan_local()

assert dummy_t.a == [
	'connect',
	'update_iterators test,0',
	'update_iterators test,1',
	'update_iterators test,2',
	'check_pending_iterators',
	'update_iterators test,3',
	'update_iterators test,4',
	'check_pending_iterators',
	'update_iterators test,5',
	'update_iterators test,6',
	'check_pending_iterators']

